function supportstorage() {
	if (typeof window.localStorage=='object') 
		return true;
	else
		return false;		
}

function handleSaveLayout() {
	var e = $(".demo").html();
	if (!stopsave && e != window.demoHtml) {
		stopsave++;
		window.demoHtml = e;
		saveLayout();
		stopsave--;
	}
}

var layouthistory; 

function saveLayout(){
	var data = layouthistory;
	if (!data) {
		data={};
		data.count = 0;
		data.list = [];
	}
	if (data.list.length>data.count) {
		for (i=data.count;i<data.list.length;i++)
			data.list[i]=null;
	}
	data.list[data.count] = window.demoHtml;
	data.count++;
	if (supportstorage()) {
		localStorage.setItem("layoutdata",JSON.stringify(data));
	}
	layouthistory = data;
	//console.log(data);

}


function undoLayout() {
	var data = layouthistory;
	//console.log(data);
	if (data) {
		if (data.count<2) return false;
		window.demoHtml = data.list[data.count-2];
		data.count--;
		$('.demo').html(window.demoHtml);
		if (supportstorage()) {
			localStorage.setItem("layoutdata",JSON.stringify(data));
		}
		return true;
	}
	return false;

}

function redoLayout() {
	var data = layouthistory;
	if (data) {
		if (data.list[data.count]) {
			window.demoHtml = data.list[data.count];
			data.count++;
			$('.demo').html(window.demoHtml);
			if (supportstorage()) {
				localStorage.setItem("layoutdata",JSON.stringify(data));
			}
			return true;
		}
	}
	return false;

}

//handleJs
function handleJsIds() {
	
}

function randomNumber() {
	return randomFromInterval(1, 1e6)
}
function randomFromInterval(e, t) {
	return Math.floor(Math.random() * (t - e + 1) + e)
}

/*栅格辅助配置*/
function gridSystemGenerator() {
	var grids=12;
	$(".lyrow .preview input").bind("keyup", function() {
		if($(this).parent().hasClass('grids')){
			grids=parseInt($(this).val());
		}else{
			var e = 0;
			var t = "";
			var n = $(this).val().split(" ", grids);
			$.each(n, function(n, r) {
				e = e + parseInt(r);
				t += '<div class="span-' + r + ' ui-sortable"></div>';
			});
			if (e === grids) {
				$(this).parent().next().find('.row').html(t);
				$(this).parents('.lyrow').find('.drag').show()
			} else {
				$(this).parents('.lyrow').find('.drag').hide()
			}
		}
	})
}


function removeElm() {
	$(".demo").delegate(".remove", "click", function(e) {
		e.preventDefault();
		$(this).parent().remove();
		if (!$(".demo .lyrow").length > 0) {
			clearDemo()
		}
	})
}
function clearDemo() {
	$(".demo").empty();
	layouthistory = null;
	if (supportstorage())
		localStorage.removeItem("layoutdata");
}
function removeMenuClasses() {
	$("#menu-layoutit li button").removeClass("active")
}
function changeStructure(wrap, e, t) {
	$(wrap).find('.' + e).each(function(index, element) {
        $(element).removeClass(e).addClass(t);
    });
}
function cleanHtml(e) {
	$(e).parent().append($(e).children().html());
	return $(e);
}

var currentDocument = null;
var timerSave = 1000;
var stopsave = 0;
var startdrag = 0;
var demoHtml = $(".demo").html();
var currenteditor = null;
$(window).resize(function() {
	$(".demo").css("min-height", $(window).height() - 160)
});

function restoreData(){
	if (supportstorage()) {
		layouthistory = JSON.parse(localStorage.getItem("layoutdata"));
		if (!layouthistory) return false;
		window.demoHtml = layouthistory.list[layouthistory.count-1];
		if (window.demoHtml) $(".demo").html(window.demoHtml);
	}
}
//代码过滤
function downloadLayoutSrc() {
	var e = "";
	var t = $("#download-layout");
	t.html($(".demo").html());
	t.find('.FULLROWTEMP').removeClass('FULLROWTEMP');
	t.find(".preview, .fullrow, .drag, .remove, .spacing").remove();
	t.find(".lyrow").addClass("removeClean");
	t.find(".box-element").addClass("removeClean");
	t.find(".lyrow .lyrow .lyrow .lyrow .lyrow .removeClean").each(function() {
		cleanHtml(this)
	});
	t.find(".lyrow .lyrow .lyrow .lyrow .removeClean").each(function() {
		cleanHtml(this)
	});
	t.find(".lyrow .lyrow .lyrow .removeClean").each(function() {
		cleanHtml(this)
	});
	t.find(".lyrow .lyrow .removeClean").each(function() {
		cleanHtml(this)
	});
	t.find(".lyrow .removeClean").each(function() {
		cleanHtml(this)
	});
	t.find(".removeClean").each(function() {
		cleanHtml(this)
	});
	t.find(".removeClean").remove();
	
	t.find("div[class*='span']").removeClass("ui-sortable");

	formatSrc = $.htmlClean($("#download-layout").html(), {
		format: true,
		allowedAttributes: [
			["id"],
			["class"]
		]
	});
	$("#download-layout").html(formatSrc);
	$("#downloadModal textarea").empty();
	$("#downloadModal textarea").val(formatSrc)
}
function initContainer(){
	$(".demo, .demo div[class*='span']").sortable({
		connectWith: "div[class*='span']",
		opacity: .35,
		handle: ".drag",
		start: function(e,t) {
			if (!startdrag) stopsave++;
			startdrag = 1;
		},
		stop: function(e,t) {
			if(stopsave>0) stopsave--;
			startdrag = 0;
			if($(t.item).parents('.wrap').length){
				$(t.item).find('.fullrow').remove();
			}
		}
	});
}

$(document).ready(function() {
	$(".demo").css("min-height", $(window).height() - 160);
	restoreData();
	$(".sidebar-nav .lyrow").draggable({
		connectToSortable: ".demo",
		helper: "clone",
		handle: ".drag",
		start: function(e,t) {
			if (!startdrag) stopsave++;
			startdrag = 1;
		},
		drag: function(e, t) {
			t.helper.width(400)
		},
		stop: function(e, t) {
			$(".demo div[class*='span']").sortable({
				opacity: .35,
				connectWith: "div[class*='span']",
				start: function(e,t) {
					if (!startdrag) stopsave++;
					startdrag = 1;
				},
				stop: function(e,t) {
					if(stopsave>0) stopsave--;
					startdrag = 0;
				}
			});
			if(stopsave>0) stopsave--;
			startdrag = 0;
		}
	});
	$(".sidebar-nav .box").draggable({
		connectToSortable: "div[class*='span']",
		helper: "clone",
		handle: ".drag",
		start: function(e,t) {
			if (!startdrag) stopsave++;
			startdrag = 1;
		},
		drag: function(e, t) {
			t.helper.width(400)
		},
		stop: function() {
			handleJsIds();
			if(stopsave>0) stopsave--;
			startdrag = 0;
		}
	});
	initContainer();

	//可视化编辑
	$("#edit").click(function() {
		$("body").removeClass("devpreview sourcepreview").addClass("edit");
		removeMenuClasses();
		$(this).addClass("active");
		return false
	});
	$("#clear").click(function(e) {
		e.preventDefault();
		clearDemo()
	});
	//预览
	$("#devpreview").click(function() {
		$("body").removeClass("edit sourcepreview").addClass("devpreview");
		removeMenuClasses();
		$(this).addClass("active");
		return false
	});
	//生成 
	$("[data-target=#downloadModal]").click(function(e) {
		e.preventDefault();
		downloadLayoutSrc();
	});
	
	$(".nav-header").click(function() {
		$(".sidebar-nav .boxes, .sidebar-nav .rows").hide();
		$(this).next().slideDown()
	});
	$('#undo').click(function(){
		stopsave++;
		if (undoLayout()) initContainer();
		stopsave--;
	});
	$('#redo').click(function(){
		stopsave++;
		if (redoLayout()) initContainer();
		stopsave--;
	});
	removeElm();
	gridSystemGenerator();
	setInterval(function() {
		handleSaveLayout()
	}, timerSave);
	//栅格间距切换
	$('body').on('click','.spacing',function(){
		var view = $(this).parent('.lyrow').children('.view');
		var e = view.children('.wrap');
		var c1, c2;
		if(view.children('.FULLROWTEMP').length){
			e = view.children('.FULLROWTEMP').children('.wrap');
		}
		if(e.children('.row').length){
			c1 = 'row';
			c2 = 'full-row';
		}else{
			c1 = 'full-row';
			c2 = 'row';
		}
		changeStructure(e,c1,c2)
	})
	//通栏布局
	function infoBlank (){
		var info = {
			tagname:"div",
			class:"",
			wrap:true
		};
		return 	info
	}
	$('body').on('click','.fullrow',function(){
		var view = $(this).parent('.lyrow').children('.view');
		var info = infoBlank();
		var e ;
		if(view.children('.FULLROWTEMP').length){
			if(view.children('.FULLROWTEMP').children('.wrap').length){
				e = view.children('.FULLROWTEMP').children('.wrap');
			}else{
				e = view.children('.FULLROWTEMP');	
				info.wrap = false;	
			}
			info.class = view.children('.FULLROWTEMP').attr('class').replace('FULLROWTEMP','');
			info.tagname = view.children('.FULLROWTEMP').get(0).nodeName.toLowerCase();	
		}else{
			e = view.children('.wrap');
		}
        fullRowClass(e, info); 
	})
	function fullRowClass(wrap,info){
		var tagName, addClass;	
		!info.wrap && $('#nowrap').attr('check',true);
		$('#wrapClassInput').val(info.class);
		switch (info.tagname){
			case "header":
				$('#tagToHeader').attr('checked',true).siblings('input:radio').removeAttr('checked');
				break;
			case "footer":
				$('#tagToFooter').attr('checked',true).siblings('input:radio').removeAttr('checked');
				break;
			default:
				$('#tagToDiv').attr('checked',true).siblings('input:radio').removeAttr('checked');
		}
		$('#wrapClassForm').unbind();
		$('#wrapClassForm').on('click','input:radio',function(){
			switch ($(this).val()){
				case "header":
					info.tagname = 'header'	;
					break;
				case "footer":
					info.tagname = 'footer'	;
					break;
				default:
					info.tagname = 'div';	
			}
			
		})
		$('#wrapClassForm').on('click',function(){
			if($('#nowrap:checked').length){
				info.wrap = false;	
			}else{
				info.wrap = true;		
			}
			
		})
		$('#wrapClassForm').on('submit',function(e){
			e.preventDefault();	
			info.class = $('#wrapClassInput').val();

			if(typeof(info)==='object'){
				tagName = info.tagname;
				addClass = info.class;	
			}
			if(!info.wrap){
				wrap = wrap.children();
				if(wrap.parent().hasClass('wrap')){
					console.log(1)
					wrap.parents('.view').append(wrap).find('.wrap').remove();	
				}
				
			}else{
				if(wrap.hasClass('FULLROWTEMP')){
					wrap.children().wrap('<div class="wrap"></div>');
					wrap = wrap.children('.wrap');
				}
			};
			if(wrap.parents('.FULLROWTEMP').length){
				var oldP = 	wrap.parents('.FULLROWTEMP');
			}else{
				wrap.wrap('FULLROWTEMP_temp');
				var oldP = 	wrap.parent('.FULLROWTEMP_temp');		
			}
			oldP.parent().append(wrap);
			oldP.remove();
			wrap.wrap('<'+ tagName +' class="FULLROWTEMP ' + addClass +'" />');
			downloadLayoutSrc();
			$('#wrapClass').modal('hide');
		})
	}
})
